#include <opencv2/opencv.hpp>

// =================.cpp文件==============
struct Detection {
    cv::Rect box;
    float conf;
    size_t clas_id;
};

unsigned char *Img2Data(const cv::Mat &img) {
    // new一个数组，存放一维展开的图像
    auto *imgdata = new unsigned char[img.rows * img.cols * img.channels()];
    for (int i = 0; i < img.rows; i++) {
        auto *data = img.ptr<unsigned char>(i);
        for (int j = 0; j < img.cols * 3; j++) {
            imgdata[i * img.cols * 3 + j] = data[j];
        }
    }
    return imgdata;
}

std::vector<Detection> Array2Box(Detection_ *result, const size_t &result_size) {
    std::vector<Detection> result_box;
    for (size_t i = 0; i < result_size; i++) {
        Detection b_a{};
        auto result_ = result[i];
        b_a.clas_id = result_.clas_id;
        b_a.conf = result_.conf;
        b_a.box.x = result_.box_array[0];
        b_a.box.y = result_.box_array[1];
        b_a.box.width = result_.box_array[2];
        b_a.box.height = result_.box_array[3];

        result_box.emplace_back(b_a);
    }
    return result_box;
}


std::vector<cv::Scalar> SetColor(const size_t &num_classes) {
    int size = 3;  // 最多有 3^3=27 种颜色
    int *arr_b = new int[size]{0, 255, 128};
    int *arr_g = new int[size]{255, 128, 0};
    int *arr_r = new int[size]{128, 0, 255};

    // 存储画框颜色
    std::vector<cv::Scalar> clas_colors;
    cv::Scalar color;
    // 循环类别总数
    for (int i = 0; i < num_classes; i++) {
        // 转成5进制数
        int c = i % size;
        int ab = (int) i / size;
        int b = ab % 10;
        int a = (int) ab / 10;

        color = cv::Scalar(arr_b[a], arr_g[b], arr_r[c]);

        clas_colors.emplace_back(color);
    }

    delete[] arr_b;
    delete[] arr_g;
    delete[] arr_r;

    return clas_colors;
}

// 画框
void DrawImg(cv::Mat &img, const std::vector<Detection> &reslult, const std::vector<std::string> &class_names,
             std::vector<cv::Scalar> colors) {
    for (const Detection &detection: reslult) {
        size_t clas_index = detection.clas_id;
        int conf = (int) std::round(detection.conf * 100);
        int x = detection.box.x;
        int y = detection.box.y;
        int h = detection.box.height;
        int w = detection.box.width;

        // 使用框的h,w进行过滤

        std::string label = class_names[clas_index] + ": 0." + std::to_string(conf);

        cv::Scalar color = colors[clas_index];
        // 画框
        cv::rectangle(img, detection.box, color, 3);
        // 写字
        cv::putText(img, label, cv::Point(x, y - 8), cv::LINE_AA, 1.2, color, 3);
    }
}




